﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;

namespace OutOrderToSubmitService
{
    public partial class OutOrderToSubmitService : ServiceBase
    {
        //提交记录数据库连接字符串
        string strConnectionStringTJ = "Data Source=192.168.1.1;Initial Catalog=DefualtDataBase;Persist Security Info=True;User ID=sa;Password=856518armyman";
        //TPAMAIN数据库连接字符串
        string strConnectionStringTP = "Data Source=192.168.1.1;Initial Catalog=TPAMain;Persist Security Info=True;User ID=sa;Password=856518armyman";
        //检查出库单时间间隔
        int iInterval = 30000;
        //检查是否有新的已审核的出库单的字符串
        string strDefaultSelectString1 = "select gxck001 出库单号,gxck005 出库部门,gxck002 出库日期,gxck010 合同编号,gxck011 合同项次,gxck007 工单号,gxck012 产品编号,gxck015 出库数量,gxck017 流转卡号,gxck021 生产日期,gxck022 淘汰率,gxck023 筛选数,gxck024 出库单备注,gxck036 DPA数量,gxck037 试验数量,gxck038 温冲数量,gxck039 包装员,出库状态=case when gxck016='Y' then '正常出库' when gxck016='K' then '编带出库' else '未出库' end,工单类型=case when gd040 like '%二筛%' then '二筛' else '普通' end from gxck_table left join gd_table on gd001=gxck007 where (gxck016='Y' or gxck016='K') and imported=0 and gxck010<>'' and gxck025 is null";
        //检查合同信息
        string strDefaultSelectString2 = "select hta001 订单编号,htb002 订单项次,hta003 客户编号,hta011 合同号,htb006 合同数量,htb008 单价,htb010 交货期,htb021 技术条件,htb022 协议,hta029 验收方式,htb027 用户计划号,htb032 备注 from hta_table ,htb_table where hta001=htb001 and htb001='@HTBH' and htb002='@HTXC'";
        //检查已验数量
        string strGetOriginalCKQuantity = "select sum(gxck015-gxck019) from gxck_table where (gxck016='Y' or gxck016='K') and gxck010='@订单编号' and gxck011='@订单项次'";
        //插入提交记录
        string strInsertString = "insert into QZKFC (提交时间,提交库房,生产日期,合同号,合同数量,已验数量,提交数量,型号,尺寸,特性,电压,容量,引出端形式,单价,技术条件,批号,芯片号,筛选数量,淘汰率,验收方式,导入标志,备注,订单编号,订单项次,高代低,DPA数量,试验数量,温冲数量,交货期,包装员,执行标准,质量等级,编带,用户计划号,出库单号,附加协议) values (convert(char(10),getutcdate(),120),@提交库房,@生产日期,@合同号,@合同数量,@已验数量,@提交数量,@型号,@尺寸,@特性,@电压,@容量,@引出端形式,@单价,@技术条件,@批号,@芯片号,@筛选数量,@淘汰率,@验收方式,1,@备注,@订单编号,@订单项次,@高代低,@DPA数量,@试验数量,@温冲数量,@交货期,@包装员,@执行标准,@质量等级,@编带,@用户计划号,@出库单号,@附加协议)";
        //查询工单信息
        string strSearchGDInfo = "select gd001 工单号,gd007 型号规格,gd025 工单类型 ,gd026 来源工单,gd034 批号 from gd_table where gd001='@GDNo'";
        //查询工单入库时批号
        string strGetRKSN = "select rk008 批号 from gxrk_table where rk031='@GDNo' and rk008 like '%/%'";
        //更新导入标记
        string strUpdateString = "update gxck_table set imported=@状态 where gxck001='@CKDH'";
        //日志文件名
        string strLogFileName;
        //发生错误的出库单池
        List<string> lstWrongIDPool;
        //计时器
        Timer t;

        public OutOrderToSubmitService()
        {
            InitializeComponent();
            lstWrongIDPool = new List<string>();
        }

        public void iniLogFile()
        {
            DirectoryInfo di = new DirectoryInfo("d:\\otsLog\\"+DateTime.Now.Year .ToString ()+"\\"+DateTime .Now .Month .ToString ("00"));
            if (!di.Exists)
            {
                di.Create();
            }
            strLogFileName = "d:\\otsLog\\" + DateTime.Now.Year.ToString() + "\\" + DateTime.Now.Month.ToString("00") + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        }

        void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            StartImport();
        }

        private SqlConnection GetConnection(DatabaseConnectionMode Mode)
        {
            SqlConnection tmpconn;
            if (Mode == DatabaseConnectionMode.TJ)
            {
                tmpconn = new SqlConnection(strConnectionStringTJ);
            }
            else
            {
                tmpconn = new SqlConnection(strConnectionStringTP);
            }
            return tmpconn;
        }

        private void OpenConnection(SqlConnection tmpconn)
        {
            try
            {
                tmpconn.Open();
            }
            catch
            { }
        }

        private void CloseConnection(SqlConnection tmpconn)
        {
            try
            {
                tmpconn.Close();
            }
            catch
            { }
        }

        private DataTable GetDataTable(string strTmpSelectString, DatabaseConnectionMode Mode)
        {
            SqlConnection tmpconn = GetConnection(Mode);
            SqlDataAdapter tmpsda = new SqlDataAdapter(strTmpSelectString, tmpconn);
            DataTable tmpdt = new DataTable();
            OpenConnection(tmpconn);
            tmpsda.Fill(tmpdt);
            CloseConnection(tmpconn);
            tmpconn.Dispose();
            return tmpdt;
        }

        private Object GetSqlData(string strTmpCmd, DatabaseConnectionMode Mode)
        {
            SqlConnection tmpconn = GetConnection(Mode);
            SqlCommand tmpcmd = new SqlCommand(strTmpCmd, tmpconn);
            Object r;
            OpenConnection(tmpconn);
            r = tmpcmd.ExecuteScalar();
            CloseConnection(tmpconn);
            tmpconn.Dispose();
            return r;
        }

        private int DoCommand(SqlCommand tmpcmd, DatabaseConnectionMode Mode)
        {
            int r;
            SqlConnection tmpconn = GetConnection(Mode);
            tmpcmd.Connection = tmpconn;
            OpenConnection(tmpconn);
            r = tmpcmd.ExecuteNonQuery();
            CloseConnection(tmpconn);
            return r;
        }

        private int DoCommand(string strCmdText, DatabaseConnectionMode Mode)
        {
            int r;
            SqlConnection tmpconn = GetConnection(Mode);
            SqlCommand tmpcmd = new SqlCommand(strCmdText, tmpconn);
            tmpcmd.Connection = tmpconn;
            OpenConnection(tmpconn);
            r = tmpcmd.ExecuteNonQuery();
            CloseConnection(tmpconn);
            return r;
        }

        public bool isExists(string str)
        {
            return Regex.Matches(str, "[a-zA-Z]").Count > 0;
        }

        private string GetString(object tmpobj)
        {
            try
            {
                return tmpobj.ToString().Trim();
            }
            catch
            {
                return string.Empty;
            }
        }

        private void StartImport()
        {
            t.Enabled = false;
            iniLogFile();
            DataTable tmpdt = GetDataTable(strDefaultSelectString1, DatabaseConnectionMode.TP);
            if (tmpdt.Rows.Count > 0)
            {
                for (int i = 0; i < tmpdt.Rows.Count; i++)
                {
                    string ir = ImportData(tmpdt.Rows[i]);
                    if (ir == string.Empty)  //导入成功
                    {
                        DoCommand(strUpdateString.Replace ("@状态","1")
                                                                     .Replace("@CKDH", GetString(tmpdt.Rows[i]["出库单号"])), DatabaseConnectionMode.TP);
                        WriteToLogFile(DateTime.Now.ToString() + "\t导入成功(" + GetString(tmpdt.Rows[i]["出库单号"]) + ")");
                    }
                    else            //导入失败
                    {
                        string strWrongID = GetString(tmpdt.Rows[i]["出库单号"]);
                        bool bIDExist = false;
                        if (ir.Contains("合同编号不符合系统要求，判断为老合同"))
                        {
                            DoCommand(strUpdateString.Replace("@状态", "1")
                                                                         .Replace("@CKDH", strWrongID), DatabaseConnectionMode.TP);
                        }
                        else
                        {
                            DoCommand(strUpdateString.Replace("@状态", "-1")
                                                                         .Replace("@CKDH", strWrongID), DatabaseConnectionMode.TP);
                        }
                        WriteToLogFile(DateTime.Now.ToString() + "\t导入失败(" + GetString(tmpdt.Rows[i]["出库单号"]) + ")\t错误信息：" + ir);
                        //foreach (string strTmp in lstWrongIDPool)
                        //{
                        //    if (strTmp == strWrongID)
                        //    {
                        //        bIDExist = true;
                        //        break;
                        //    }
                        //}
                        //if (!bIDExist)
                        //{
                        //    lstWrongIDPool.Add(strWrongID);
                        //    WriteToLogFile(DateTime.Now.ToString() + "\t导入失败(" + GetString(tmpdt.Rows[i]["出库单号"]) + ")\t错误信息：" + ir);
                        //}
                    }
                }
            }
            t.Enabled = true;
        }

        private string ImportData(DataRow tmpr)
        {
            try
            {
                SqlCommand tmpcmd = new SqlCommand(strInsertString);
                //tmpcmd.Parameters.Add("@提交时间", SqlDbType.DateTime);
                tmpcmd.Parameters.Add("@提交库房", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@生产日期", SqlDbType.DateTime);
                tmpcmd.Parameters.Add("@合同号", SqlDbType.VarChar);    //合同取
                tmpcmd.Parameters.Add("@合同数量", SqlDbType.Int);      //合同取
                tmpcmd.Parameters.Add("@已验数量", SqlDbType.Int);
                tmpcmd.Parameters.Add("@提交数量", SqlDbType.Int);
                tmpcmd.Parameters.Add("@型号", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@尺寸", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@特性", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@电压", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@容量", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@引出端形式", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@单价", SqlDbType.Decimal);     //合同取
                tmpcmd.Parameters.Add("@技术条件", SqlDbType.VarChar); //合同取
                tmpcmd.Parameters.Add("@批号", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@芯片号", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@筛选数量", SqlDbType.Char);
                tmpcmd.Parameters.Add("@淘汰率", SqlDbType.Char);
                tmpcmd.Parameters.Add("@验收方式", SqlDbType.VarChar);      //合同取
                tmpcmd.Parameters.Add("@备注", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@订单编号", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@订单项次", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@高代低", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@DPA数量", SqlDbType.Char);
                tmpcmd.Parameters.Add("@试验数量", SqlDbType.Char);
                tmpcmd.Parameters.Add("@温冲数量", SqlDbType.Char);
                tmpcmd.Parameters.Add("@交货期", SqlDbType.Char);
                tmpcmd.Parameters.Add("@包装员", SqlDbType.Char);
                tmpcmd.Parameters.Add("@执行标准", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@质量等级", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@编带", SqlDbType.Bit);
                tmpcmd.Parameters.Add("@用户计划号", SqlDbType.VarChar );
                tmpcmd.Parameters.Add("@出库单号", SqlDbType.VarChar);
                tmpcmd.Parameters.Add("@附加协议", SqlDbType.VarChar);
                //gxck002 出库日期,gxck010 合同编号,gxck011 合同项次,gxck012 产品编号,gxck015 出库数量,gxck017 流转卡号,gxck021 生产日期,gxck022 淘汰率,gxck023 筛选数
                //tmpcmd.Parameters["@提交时间"].Value = ConvertToDateTime(tmpr["出库日期"].ToString());
                
                if (GetString(tmpr["产品编号"]).StartsWith("J-") || GetString(tmpr["产品编号"]).StartsWith("M-"))
                {
                    tmpcmd.Parameters["@提交库房"].Value = "一般品库";
                }
                else
                {
                    tmpcmd.Parameters["@提交库房"].Value = "七专库";
                }
                tmpcmd.Parameters["@出库单号"].Value = GetString(tmpr["出库单号"]);
                tmpcmd.Parameters["@生产日期"].Value = ConvertToDateTime(GetString(tmpr["生产日期"]));
                tmpcmd.Parameters["@提交数量"].Value = Convert.ToInt32(tmpr["出库数量"]);
                tmpcmd.Parameters["@包装员"].Value = StringHandler(tmpr["包装员"]);
                if (GetString(tmpr["出库状态"]).Equals("编带出库"))
                {
                    tmpcmd.Parameters["@编带"].Value = 1;
                }
                else
                {
                    tmpcmd.Parameters["@编带"].Value = 0;
                }
                string strTmpModel = tmpr["产品编号"].ToString().Trim();
                if (strTmpModel.Contains("(") && strTmpModel.IndexOf('(') > strTmpModel.IndexOf('-'))
                {
                    strTmpModel = strTmpModel.Split('(').GetValue(0).ToString();
                }
                if (strTmpModel.Contains("（") && strTmpModel.IndexOf('（') > strTmpModel.IndexOf('-'))
                {
                    strTmpModel = strTmpModel.Split('（').GetValue(0).ToString();
                }
                if(strTmpModel .EndsWith ("-Z")|| strTmpModel.EndsWith("-M") || strTmpModel.EndsWith("-T") || strTmpModel.EndsWith("-E") || strTmpModel.EndsWith("-R") || strTmpModel.EndsWith("-2") || strTmpModel.EndsWith("-A"))
                {
                    tmpcmd.Parameters["@引出端形式"].Value = strTmpModel.Substring(strTmpModel.Length - 1, 1);
                    strTmpModel = strTmpModel.Substring(0,strTmpModel.Length - 2);
                }
                else
                {
                    tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                }
                string[] tmpp = strTmpModel.Split('-');
                #region 新算法
                switch (tmpp.Length )
                {
                    case 5:
                        if (tmpp[1].Contains("0"))
                        {
                            //M-HCC4101-CG-50V-271J
                            tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                            tmpcmd.Parameters["@型号"].Value = tmpp[1];
                            tmpcmd.Parameters["@特性"].Value = tmpp[2];
                            tmpcmd.Parameters["@电压"].Value = tmpp[3];
                            tmpcmd.Parameters["@容量"].Value = tmpp[4];
                            tmpcmd.Parameters["@尺寸"].Value = DBNull.Value;
                            //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                        }
                        else
                        {
                            //?
                            tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                            tmpcmd.Parameters["@型号"].Value = tmpp[1];
                            tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                            tmpcmd.Parameters["@电压"].Value = tmpp[3];
                            tmpcmd.Parameters["@容量"].Value = tmpp[4];
                            tmpcmd.Parameters["@特性"].Value = DBNull.Value;
                            //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                        }
                        break;
                    case 6:
                        if (GetString(tmpr["产品编号"]).StartsWith("SAST"))
                        {
                            //SAST-CC41L-0805-CG-100V-104K
                            tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                            tmpcmd.Parameters["@型号"].Value = tmpp[1];
                            tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                            tmpcmd.Parameters["@特性"].Value = tmpp[3];
                            tmpcmd.Parameters["@电压"].Value = tmpp[4];
                            tmpcmd.Parameters["@容量"].Value = tmpp[5];
                            //tmpcmd.Parameters["@引出端形式"].Value = tmpp[6];
                        }
                        else
                        {
                            //G-CT41L-0805-2C1-50V-104K
                            tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                            tmpcmd.Parameters["@型号"].Value = tmpp[1];
                            tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                            tmpcmd.Parameters["@特性"].Value = tmpp[3];
                            tmpcmd.Parameters["@电压"].Value = tmpp[4];
                            tmpcmd.Parameters["@容量"].Value = tmpp[5];
                            //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                        }
                        break;
                    case 7:
                        if (GetString(tmpr["产品编号"]).Contains("C041"))
                        {
                                //QJ-C041-Ba-1-CG-63V-121K
                                tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                                tmpcmd.Parameters["@型号"].Value = tmpp[1] + "-" + tmpp[2];
                                tmpcmd.Parameters["@尺寸"].Value = tmpp[3];
                                tmpcmd.Parameters["@特性"].Value = tmpp[4];
                                tmpcmd.Parameters["@电压"].Value = tmpp[5];
                                tmpcmd.Parameters["@容量"].Value = tmpp[6];
                                //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                        }
                        else if (GetString(tmpr["产品编号"]).StartsWith("SAST-G"))
                        {
                            //SAST-G-CC41L-0805-CG-100V-104K
                            tmpcmd.Parameters["@质量等级"].Value = tmpp[0].ToString() + "-" + tmpp[1].ToString();
                            tmpcmd.Parameters["@型号"].Value = tmpp[2];
                            tmpcmd.Parameters["@尺寸"].Value = tmpp[3];
                            tmpcmd.Parameters["@特性"].Value = tmpp[4];
                            tmpcmd.Parameters["@电压"].Value = tmpp[5];
                            tmpcmd.Parameters["@容量"].Value = tmpp[6];
                            //tmpcmd.Parameters["@引出端形式"].Value = tmpp[6];
                        }
                        else if (GetString(tmpr["产品编号"]).Contains("CT41P"))
                        {
                            //M-CT41P-01-5868x1L-X7Q-2KV-124M
                            //J-CT41P-01-5868×2L-X7Q-2KV-244M
                            tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                            tmpcmd.Parameters["@型号"].Value = tmpp[1] + "-" + tmpp[2];
                            tmpcmd.Parameters["@尺寸"].Value = tmpp[3];
                            tmpcmd.Parameters["@特性"].Value = tmpp[4];
                            tmpcmd.Parameters["@电压"].Value = tmpp[5];
                            tmpcmd.Parameters["@容量"].Value = tmpp[6];
                            //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                        }
                        break;
                    default:
                        return "产品编号转换错误！";
                        break;
                }
                #endregion
                #region 旧算法
                //if (tmpp.Length == 6)
                //{
                //    tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                //    tmpcmd.Parameters["@型号"].Value = tmpp[1];
                //    tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                //    tmpcmd.Parameters["@特性"].Value = tmpp[3];
                //    tmpcmd.Parameters["@电压"].Value = tmpp[4];
                //    tmpcmd.Parameters["@容量"].Value = tmpp[5];
                //    //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                //}
                //else if (tmpp.Length == 5)
                //{
                //    if (tmpp[1].Contains("0"))
                //    {
                //        tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                //        tmpcmd.Parameters["@型号"].Value = tmpp[1];
                //        tmpcmd.Parameters["@特性"].Value = tmpp[2];
                //        tmpcmd.Parameters["@电压"].Value = tmpp[3];
                //        tmpcmd.Parameters["@容量"].Value = tmpp[4];
                //        tmpcmd.Parameters["@尺寸"].Value = DBNull.Value;
                //        //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                //    }
                //    else
                //    {
                //        tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                //        tmpcmd.Parameters["@型号"].Value = tmpp[1];
                //        tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                //        tmpcmd.Parameters["@电压"].Value = tmpp[3];
                //        tmpcmd.Parameters["@容量"].Value = tmpp[4];
                //        tmpcmd.Parameters["@特性"].Value = DBNull.Value;
                //        //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                //    }
                //}
                //else if (tmpp.Length == 7 && (GetString(tmpr["产品编号"]).Contains("C041")))
                //{
                    
                //    tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                //    tmpcmd.Parameters["@型号"].Value = tmpp[1] + "-" + tmpp[2];
                //    tmpcmd.Parameters["@尺寸"].Value = tmpp[3];
                //    tmpcmd.Parameters["@特性"].Value = tmpp[4];
                //    tmpcmd.Parameters["@电压"].Value = tmpp[5];
                //    tmpcmd.Parameters["@容量"].Value = tmpp[6];
                //    //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                //}
                //else if (tmpp.Length == 7 && (GetString(tmpr["产品编号"]).StartsWith("SAST-G")))
                //{
                //    //SAST-G-CC41L-0805-CG-100V-104K
                //    tmpcmd.Parameters["@质量等级"].Value = tmpp[0].ToString ()+"-"+ tmpp[1].ToString();
                //    tmpcmd.Parameters["@型号"].Value = tmpp[2];
                //    tmpcmd.Parameters["@尺寸"].Value = tmpp[3];
                //    tmpcmd.Parameters["@特性"].Value = tmpp[4];
                //    tmpcmd.Parameters["@电压"].Value = tmpp[5];
                //    tmpcmd.Parameters["@容量"].Value = tmpp[6];
                //    //tmpcmd.Parameters["@引出端形式"].Value = tmpp[6];
                //}
                //else if (tmpp.Length == 7 && (GetString(tmpr["产品编号"]).StartsWith("SAST")))
                //{
                //    //SAST-CC41L-0805-CG-100V-104K-Z
                //    tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                //    tmpcmd.Parameters["@型号"].Value = tmpp[1];
                //    tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                //    tmpcmd.Parameters["@特性"].Value = tmpp[3];
                //    tmpcmd.Parameters["@电压"].Value = tmpp[4];
                //    tmpcmd.Parameters["@容量"].Value = tmpp[5];
                //    //tmpcmd.Parameters["@引出端形式"].Value = tmpp[6];
                //}
                //else if (tmpp.Length == 7 && (GetString(tmpr["产品编号"]).StartsWith("CT41P")))
                //{
                //    //J-CT41P-01-5868×2L-X7Q-2KV-244M
                //    tmpcmd.Parameters["@质量等级"].Value = tmpp[0] ;
                //    tmpcmd.Parameters["@型号"].Value = tmpp[1] + "-" + tmpp[2];
                //    tmpcmd.Parameters["@尺寸"].Value = tmpp[3];
                //    tmpcmd.Parameters["@特性"].Value = tmpp[4];
                //    tmpcmd.Parameters["@电压"].Value = tmpp[5];
                //    tmpcmd.Parameters["@容量"].Value = tmpp[6];
                //    //tmpcmd.Parameters["@引出端形式"].Value = DBNull.Value;
                //}
                //else if(tmpp.Length ==7)
                //{
                //    //G+-CC411-0505-BA-150V-100J-T
                //    tmpcmd.Parameters["@质量等级"].Value = tmpp[0];
                //    tmpcmd.Parameters["@型号"].Value = tmpp[1];
                //    tmpcmd.Parameters["@尺寸"].Value = tmpp[2];
                //    tmpcmd.Parameters["@特性"].Value = tmpp[3];
                //    tmpcmd.Parameters["@电压"].Value = tmpp[4];
                //    tmpcmd.Parameters["@容量"].Value = tmpp[5];
                //    //tmpcmd.Parameters["@引出端形式"].Value = tmpp[6];
                //}
                //else
                //{
                //    return "产品编号转换错误！";
                //}
                #endregion
                string strTmpSN = GetString(tmpr["流转卡号"]).Trim();
                if (strTmpSN.Contains("/"))
                {
                    strTmpSN = strTmpSN.Split('/').GetValue(0).ToString().Trim ();
                }
                tmpcmd.Parameters["@批号"].Value = strTmpSN;
                if (GetString(tmpr["产品编号"]).StartsWith("CC-"))
                {
                    if (isExists (strTmpSN.Substring (0,8)))
                    {
                        tmpcmd.Parameters["@芯片号"].Value = strTmpSN.Substring(0, 8);
                    }
                    else
                    {
                        tmpcmd.Parameters["@芯片号"].Value = GetChipNumber(tmpr["工单号"]);
                    }
                }
                else
                {
                    tmpcmd.Parameters["@芯片号"].Value = GetChipNumber(tmpr["工单号"]);
                }
                tmpcmd.Parameters["@DPA数量"].Value = StringHandler(tmpr["DPA数量"]);
                tmpcmd.Parameters["@试验数量"].Value = StringHandler(tmpr["试验数量"]);
                tmpcmd.Parameters["@温冲数量"].Value = StringHandler(tmpr["温冲数量"]);
                if (((GetString(tmpr["产品编号"]).StartsWith ("J-") || GetString(tmpr["产品编号"]).StartsWith("M-")) && GetString(tmpr["工单类型"]).Equals("二筛"))
                    || ((!GetString(tmpr["产品编号"]).StartsWith("J-")) && (!GetString(tmpr["产品编号"]).StartsWith("M-"))))
                {
                    if (GetString(tmpr["筛选数"]).Contains("."))
                    {
                        try
                        {
                            tmpcmd.Parameters["@筛选数量"].Value = GetString(tmpr["筛选数"]).Substring(0, GetString(tmpr["筛选数"]).IndexOf('.'));
                        }
                        catch
                        {
                            tmpcmd.Parameters["@筛选数量"].Value = GetString(tmpr["筛选数"]);
                        }
                    }
                    else if (GetString(tmpr["筛选数"]).Contains("-"))
                    {
                        tmpcmd.Parameters["@筛选数量"].Value = "";
                    }
                    else
                    {
                        tmpcmd.Parameters["@筛选数量"].Value = GetString(tmpr["筛选数"]);
                    }
                    if (GetString(tmpr["淘汰率"]).Contains("-"))
                    {
                        tmpcmd.Parameters["@淘汰率"].Value = "";
                    }
                    else
                    {
                        tmpcmd.Parameters["@淘汰率"].Value = GetString(tmpr["淘汰率"]);
                    }
                }
                else
                {
                    tmpcmd.Parameters["@筛选数量"].Value = "";
                    tmpcmd.Parameters["@淘汰率"].Value = "";
                }
                if (GetString(tmpr["出库单备注"]).Contains("|"))
                {
                    int iFirstIndex;
                    int iNextIndex;
                    iFirstIndex = GetString(tmpr["出库单备注"]).IndexOf('|');
                    if (iFirstIndex == GetString(tmpr["出库单备注"]).Length - 1)
                    {
                        iNextIndex = -1;
                    }
                    else
                    {
                        iNextIndex = GetString(tmpr["出库单备注"]).IndexOf('|', iFirstIndex + 1);
                    }
                    if (iFirstIndex < iNextIndex)
                    {
                        tmpcmd.Parameters["@高代低"].Value = GetString(tmpr["出库单备注"]).Substring(iFirstIndex + 1, iNextIndex - iFirstIndex);
                    }
                    else
                    {
                        tmpcmd.Parameters["@高代低"].Value = "";
                    }
                }
                else
                {
                    tmpcmd.Parameters["@高代低"].Value = "";
                }
                if (GetString(tmpr["出库单备注"]).Contains("锡铅"))
                {
                    tmpcmd.Parameters["@备注"].Value = "锡铅";
                }
                if (GetString(tmpr["出库单备注"]).Contains("2UR"))
                {
                    tmpcmd.Parameters["@备注"].Value =(GetString (tmpcmd.Parameters["@备注"].Value)+ "2UR").Trim ();
                }
                if (GetString(tmpr["出库单备注"]).Contains("2.5UR"))
                {
                    tmpcmd.Parameters["@备注"].Value = (GetString(tmpcmd.Parameters["@备注"].Value) + "2.5UR").Trim();
                }
                //取合同信息
                if (VerifyHTBH(GetString(tmpr["合同编号"])))
                {
                    DataTable tmpdtHT = GetDataTable((strDefaultSelectString2.Replace("@HTBH", GetString(tmpr["合同编号"]))).Replace("@HTXC", GetString(tmpr["合同项次"])), DatabaseConnectionMode.TP);
                    if (tmpdtHT.Rows.Count > 0)
                    {
                        //43所、771所普军产品要导入淘汰率、筛选数
                        string strTmpCustomerID= GetString(tmpdtHT.Rows[0]["客户编号"]);
                        if ((strTmpCustomerID .StartsWith ("43")|| strTmpCustomerID.StartsWith("08-43") || strTmpCustomerID.StartsWith("771")) && tmpcmd.Parameters["@质量等级"].Value.Equals ("J"))
                        {
                            if (GetString(tmpr["筛选数"]).Contains("."))
                            {
                                try
                                {
                                    tmpcmd.Parameters["@筛选数量"].Value = GetString(tmpr["筛选数"]).Substring(0, GetString(tmpr["筛选数"]).IndexOf('.'));
                                }
                                catch
                                {
                                    tmpcmd.Parameters["@筛选数量"].Value = GetString(tmpr["筛选数"]);
                                }
                            }
                            else if (GetString(tmpr["筛选数"]).Contains("-"))
                            {
                                tmpcmd.Parameters["@筛选数量"].Value = "";
                            }
                            else
                            {
                                tmpcmd.Parameters["@筛选数量"].Value = GetString(tmpr["筛选数"]);
                            }
                            if (GetString(tmpr["淘汰率"]).Contains("-"))
                            {
                                tmpcmd.Parameters["@淘汰率"].Value = "";
                            }
                            else
                            {
                                tmpcmd.Parameters["@淘汰率"].Value = GetString(tmpr["淘汰率"]);
                            }
                        }
                        //hta011 合同号,htb006 合同数量,htb008 单价,htb021 技术条件,hta029 验收方式
                        string strTmpContractNo = GetString(tmpdtHT.Rows[0]["合同号"]);
                        if (strTmpContractNo.Contains("宏科片"))
                        {
                            tmpcmd.Parameters["@合同号"].Value = DateTime.Now.ToString("yy") + "-送试";
                        }
                        else
                        {
                            if (strTmpContractNo.Contains("送样"))
                            {
                                tmpcmd.Parameters["@合同号"].Value = strTmpContractNo;
                            }
                            else
                            {
                                tmpcmd.Parameters["@合同号"].Value = strTmpContractNo.Substring(6);
                            }
                        }
                        tmpcmd.Parameters["@合同数量"].Value = Convert.ToInt32(tmpdtHT.Rows[0]["合同数量"]);
                        tmpcmd.Parameters["@单价"].Value = Convert.ToDouble(tmpdtHT.Rows[0]["单价"]);
                        tmpcmd.Parameters["@备注"].Value =GetString (tmpcmd.Parameters["@备注"].Value)+" "+GetString(tmpdtHT.Rows[0]["备注"]);
                        tmpcmd.Parameters["@用户计划号"].Value = GetString(tmpdtHT.Rows[0]["用户计划号"]);
                        tmpcmd.Parameters["@执行标准"].Value =GetString ( GetString(tmpdtHT.Rows[0]["技术条件"]));
                        string strbcxy = GetString(tmpdtHT.Rows[0]["协议"]);
                        if (strbcxy.Contains("LMS312"))
                        {
                            tmpcmd.Parameters["@附加协议"].Value = string.Empty;
                            tmpcmd.Parameters["@执行标准"].Value = GetString(tmpcmd.Parameters["@执行标准"].Value) + " " + strbcxy;
                        }
                        else
                        {
                            tmpcmd.Parameters["@附加协议"].Value = strbcxy;
                        }
                        string strjstj = GetString(tmpdtHT.Rows[0]["技术条件"]);
                        if (strjstj.Contains("QZJ840624"))
                        {
                            if (strbcxy.Length > 0)
                            {
                                tmpcmd.Parameters["@技术条件"].Value = strbcxy;
                            }
                            else
                            {
                                tmpcmd.Parameters["@技术条件"].Value = "G";
                            }
                        }
                        else if (strjstj.Contains("CAST"))
                        {
                            tmpcmd.Parameters["@技术条件"].Value = strjstj;
                        }
                        else if (strjstj.Contains("HC"))
                        {
                            tmpcmd.Parameters["@技术条件"].Value = "C";
                        }
                        else if (strbcxy.Length > 0)
                        {
                            tmpcmd.Parameters["@技术条件"].Value = strbcxy;
                        }
                        else
                        {
                            tmpcmd.Parameters["@技术条件"].Value = strjstj;
                        }
                        tmpcmd.Parameters["@验收方式"].Value = GetString(tmpdtHT.Rows[0]["验收方式"]);
                        tmpcmd.Parameters["@订单编号"].Value = GetString(tmpdtHT.Rows[0]["订单编号"]);
                        tmpcmd.Parameters["@订单项次"].Value = GetString(tmpdtHT.Rows[0]["订单项次"]);
                        tmpcmd.Parameters["@交货期"].Value = GetString(tmpdtHT.Rows[0]["交货期"]);
                        AddContractMemo(GetString(tmpcmd.Parameters["@订单编号"].Value));
                    }
                    else
                    {
                        return "在合同表中未检索到相关合同信息！";
                    }
                }
                else
                {
                    if (GetString(tmpr["合同编号"]).Contains ("送样"))
                    {
                        tmpcmd.Parameters["@合同号"].Value = GetString(tmpr["合同编号"]).Trim ();
                        tmpcmd.Parameters["@合同数量"].Value = DBNull.Value ;
                        tmpcmd.Parameters["@技术条件"].Value = DBNull.Value;
                        tmpcmd.Parameters["@执行标准"].Value = DBNull.Value;
                        tmpcmd.Parameters["@单价"].Value = DBNull.Value;
                        tmpcmd.Parameters["@备注"].Value = DBNull.Value;
                        tmpcmd.Parameters["@验收方式"].Value = DBNull.Value;
                        tmpcmd.Parameters["@订单编号"].Value = DBNull.Value;
                        tmpcmd.Parameters["@订单项次"].Value = DBNull.Value;
                        tmpcmd.Parameters["@交货期"].Value = DBNull.Value;
                    }
                    else
                    {
                        return "合同编号不符合系统要求，判断为老合同！";
                    }
                }
                //已验数量
                tmpcmd.Parameters["@已验数量"].Value = GetInt(GetSqlData(strGetOriginalCKQuantity.Replace("@订单编号", GetString(tmpr["合同编号"]))
                                                                                                                                                     .Replace("@订单项次", GetString(tmpr["合同项次"])), DatabaseConnectionMode.TP)) - GetInt(tmpr["出库数量"]);
                if (DoCommand(tmpcmd, DatabaseConnectionMode.TJ) == 1)
                {
                    return string.Empty;
                }
                else
                {
                    return "向提交表中插入记录失败！";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private int GetInt(object tmpobj)
        {
            try
            {
                return Convert.ToInt32(tmpobj);
            }
            catch
            {
                return 0;
            }
        }

        private object ConvertToDateTime(string strTmpDate)
        {
            string strDate = strTmpDate;
            try
            {
                if (strTmpDate.Contains(".") || strTmpDate.Contains("-"))
                {
                    return Convert.ToDateTime(strDate);
                }
                //20101015
                strDate = strDate.Insert(6, "-");
                strDate = strDate.Insert(4, "-");
                return Convert.ToDateTime(strDate);
            }
            catch
            {
                return DBNull.Value;
            }
        }

        private bool VerifyHTBH(string strTmpHTBH)
        {
            try
            {
                Convert.ToInt64(strTmpHTBH);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public enum DatabaseConnectionMode       //数据库连接类型
        {
            TJ = 1,       //提交
            TP = 2,       //TPAMAIN
        };

        private void WriteToLogFile(string strMsg)
        {
            try
            {
                StreamWriter sw = File.AppendText(strLogFileName);
                sw.WriteLine(strMsg);
                sw.Close();
            }
            catch(Exception ex)
            {
                EventLog.WriteEntry("OOTS", ex.Message);
            }
        }

        private void AddContractMemo(string strContractNo)
        {
            object obz = GetSqlData("select htc002 from htc_table where htc001='" + strContractNo + "'", DatabaseConnectionMode.TP);
            string strBz;
            if (obz == DBNull.Value)
            {
                strBz = string.Empty;
            }
            else
            {
                strBz = obz.ToString().Trim();
                if (strBz.Contains("'"))
                {
                    strBz = strBz.Replace("'", "‘");
                }
            }
            DataTable tmpdt = GetDataTable("select * from 订单备注表 where 订单编号='" + strContractNo + "'", DatabaseConnectionMode.TJ);
            if (tmpdt.Rows.Count > 0)
            {
                DoCommand("update 订单备注表 set 订单备注='" + strBz + "' where 订单编号='" + strContractNo + "'", DatabaseConnectionMode.TJ);
            }
            else
            {
                DoCommand("insert into 订单备注表 (订单编号,订单备注) values ('" + strContractNo + "','" + strBz + "')", DatabaseConnectionMode.TJ);
            }
        }

        private string StringHandler(object oTmp)
        {
            if (oTmp == DBNull.Value)
            {
                return string.Empty;
            }
            try
            {
                return Convert.ToString(Convert.ToInt32(oTmp));
            }
            catch
            {
                return string.Empty;
            }
        }

        private string GetChipNumber(object oGdNo)
        {
            //select gd001 工单号,gd025 工单类型 ,gd026 来源工单,gd034 批号 from gd_table where gd001='@GDNo'
            string strChipNumber = string.Empty;
            string strGdNo = string.Empty;
            if (oGdNo == DBNull.Value)
            {
                return string.Empty;
            }
            else
            {
                strGdNo = oGdNo.ToString();
            }
            //先检查入库单，如果已手工输入芯片号，则直接取该芯片号
            string strTmpSN = GetString(GetSqlData(strGetRKSN.Replace("@GDNo", strGdNo), DatabaseConnectionMode.TP));
            if (strTmpSN.Length > 0)
            {
                return GetString(strTmpSN.Split('/').GetValue(1));
            }
            //如果是CC等级产品，检查生产批号是否是10位数，如果是，则取左8位为芯片号
            DataTable tmpdt=GetDataTable (strSearchGDInfo .Replace ("GDNo",strGdNo ),DatabaseConnectionMode .TP );
            if (tmpdt.Rows.Count >0)
            {
                if (GetString (tmpdt.Rows [0]["型号规格"]).StartsWith ("CC-"))
                {
                    if (GetString (tmpdt .Rows [0]["批号"]).Length ==10)
                    {
                        if (GetInt(GetString(tmpdt.Rows[0]["批号"]).Substring(0, 8)) == 0)
                        {
                            return GetString(tmpdt.Rows[0]["批号"]).Substring(0, 8);
                        }
                    }
                }
            }
            Object oResourceGdNo = strGdNo;
            string strR = string.Empty;
            try
            {
                while (oResourceGdNo != DBNull.Value && GetString(oResourceGdNo) != string.Empty && strR == string.Empty)
                {
                    oResourceGdNo = GetResourceGdNo(oResourceGdNo, ref strR);
                }
            }
            catch
            {
                strR = string.Empty;
            }
            return strR;
        }

        private object GetResourceGdNo(object oTmpResourceGdNo, ref string strR)
        {
            string strGdNo = string.Empty;
            if (oTmpResourceGdNo != DBNull.Value)
            {
                strGdNo = oTmpResourceGdNo.ToString();
            }
            else
            {
                return DBNull.Value;
            }
            object oResourceGdNo = string.Empty;
            DataTable tmpdt = GetDataTable(strSearchGDInfo.Replace("@GDNo", strGdNo), DatabaseConnectionMode.TP);
            if (tmpdt.Rows.Count > 0)
            {
                oResourceGdNo = tmpdt.Rows[0]["来源工单"];
                if (tmpdt.Rows[0]["工单类型"].ToString() == "A")
                {
                    strR = tmpdt.Rows[0]["批号"].ToString();
                }
            }
            return oResourceGdNo;
        }

        protected override void OnStart(string[] args)
        {
            iniLogFile();
            t = new Timer();
            t.AutoReset=true ;
            t.Interval = iInterval ;
            t.Elapsed += new ElapsedEventHandler(t_Elapsed);
            t.Enabled = true;
            WriteToLogFile(DateTime.Now.ToString() + "\t服务开启");
        }

        protected override void OnStop()
        {
            t.Enabled = false;
            WriteToLogFile(DateTime.Now.ToString() + "\t服务关闭");
        }
    }
}
